<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
<script src="https://cdn.jsdelivr.net/gh/stevenjoezhang/live2d-widget@latest/autoload.js"></script>
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/picture/pika.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/picture/pika.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">
  <meta name="baidu-site-verification" content="code-LqqDM3vffE">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.css">


  <script>
  (function(i,s,o,g,r,a,m){i["DaoVoiceObject"]=r;i[r]=i[r]||function(){(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;a.charset="utf-8";m.parentNode.insertBefore(a,m)})(window,document,"script",('https:' == document.location.protocol ? 'https:' : 'http:') + "//widget.daovoice.io/widget/2efd5eff.js","daovoice")
  daovoice('init', {
    app_id: "2efd5eff"
  });
  daovoice('update');
  </script>


<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"notspr.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":true,"scrollpercent":true},"bookmark":{"enable":true,"color":"#ff7600","save":"auto"},"fancybox":true,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":false,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="前言 接着Redis数据类型来说，来谈谈Redis的具体使用场景，首先回顾一下： Redis是一种基于键值对的NoSQL数据库，它的值主要由string（字符串），hash（哈希），list（列表），set（集合），zset（有序集合）五种基本数据结构构成。那么这些数据结构的使用场景有哪些？以下将用内部编码及使用场景的方式浅析Redis的五种数据类型。">
<meta property="og:type" content="article">
<meta property="og:title" content="Redis修炼之使用场景">
<meta property="og:url" content="https://notspr.com/2020/08/16/redis-use-case/index.html">
<meta property="og:site_name" content="Sapphire">
<meta property="og:description" content="前言 接着Redis数据类型来说，来谈谈Redis的具体使用场景，首先回顾一下： Redis是一种基于键值对的NoSQL数据库，它的值主要由string（字符串），hash（哈希），list（列表），set（集合），zset（有序集合）五种基本数据结构构成。那么这些数据结构的使用场景有哪些？以下将用内部编码及使用场景的方式浅析Redis的五种数据类型。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-08-15T16:33:06.000Z">
<meta property="article:modified_time" content="2020-12-05T22:05:07.991Z">
<meta property="article:author" content="Ryan Shu">
<meta property="article:tag" content="Redis">
<meta property="article:tag" content="Redis使用场景">
<meta property="article:tag" content="NoSQL">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://notspr.com/2020/08/16/redis-use-case/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Redis修炼之使用场景 | Sapphire</title>
  


  <script data-pjax>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?2907d577c8c6c2f7fe3843736d24280d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

  <!--pjax：防止跳转页面音乐暂停-->
  <script src="https://cdn.jsdelivr.net/npm/pjax@0.2.8/pjax.js"></script>
<link rel="alternate" href="/atom.xml" title="Sapphire" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Sapphire</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">興趣使然的博客</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/aboutme/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签<span class="badge">82</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类<span class="badge">34</span></a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档<span class="badge">40</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="reading-progress-bar"></div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

  <a href="https://github.com/sususama5555" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://notspr.com/2020/08/16/redis-use-case/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/picture/avatar.jpg">
      <meta itemprop="name" content="Ryan Shu">
      <meta itemprop="description" content="全栈 | 硬件 | 篮球 | 游戏">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Sapphire">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Redis修炼之使用场景
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2020-08-16 00:33:06" itemprop="dateCreated datePublished" datetime="2020-08-16T00:33:06+08:00">2020-08-16</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" itemprop="url" rel="index"><span itemprop="name">数据库</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/Redis%E4%BF%AE%E7%82%BC/" itemprop="url" rel="index"><span itemprop="name">Redis修炼</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="far fa-file-word"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>3.6k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="far fa-clock"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>3 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <blockquote>
<h2 id="前言"><a href="#前言" class="headerlink" title="前言"></a>前言</h2></blockquote>
<p>接着Redis数据类型来说，来谈谈Redis的具体使用场景，首先回顾一下：</p>
<p>Redis是一种基于键值对的NoSQL数据库，它的值主要由string（字符串），hash（哈希），list（列表），set（集合），zset（有序集合）五种基本数据结构构成。那么这些数据结构的使用场景有哪些？以下将用内部编码及使用场景的方式浅析Redis的五种数据类型。</p>
<a id="more"></a>


<blockquote>
<h2 id="使用场景"><a href="#使用场景" class="headerlink" title="使用场景"></a>使用场景</h2></blockquote>
<h3 id="一-字符串"><a href="#一-字符串" class="headerlink" title="一 字符串"></a><strong>一 字符串</strong></h3><p>字符串类型是Redis最基础的数据结构，字符串类型可以是<code>JSON</code>、<code>XML</code>甚至是二进制的图片等数据，但是最大值不能超过512MB。</p>
<h4 id="1-1-内部编码"><a href="#1-1-内部编码" class="headerlink" title="1.1 内部编码"></a><strong>1.1 内部编码</strong></h4><p>Redis会根据当前值的类型和长度决定使用哪种内部编码来实现。</p>
<p>字符串类型的内部编码有3种：</p>
<ul>
<li>int：8个字节的长整型。</li>
<li>embstr：小于等于39个字节的字符串。</li>
<li>raw：大于39个字节的字符串。</li>
</ul>
<h4 id="1-2-使用场景"><a href="#1-2-使用场景" class="headerlink" title="1.2 使用场景"></a><strong>1.2 使用场景</strong></h4><h5 id="1-2-1-缓存"><a href="#1-2-1-缓存" class="headerlink" title="1.2.1 缓存"></a>1.2.1 缓存</h5><p>在web服务中，使用MySQL作为数据库，Redis作为缓存。由于Redis具有支撑高并发的特性，通常能起到加速读写和降低后端压力的作用。web端的大多数请求都是从Redis中获取的数据，如果Redis中没有需要的数据，则会从MySQL中去获取，并将获取到的数据写入redis。</p>
<h5 id="1-2-2-计数"><a href="#1-2-2-计数" class="headerlink" title="1.2.2 计数"></a>1.2.2 计数</h5><p>Redis中有一个字符串相关的命令<code>incr key</code>，<code>incr</code>命令对值做自增操作，返回结果分为以下三种情况：</p>
<ul>
<li>值不是整数，返回错误</li>
<li>值是整数，返回自增后的结果</li>
<li>key不存在，默认键为<code>0</code>，返回<code>1</code></li>
</ul>
<p>比如文章的阅读量，视频的播放量等等都会使用redis来计数，每播放一次，对应的播放量就会加1，同时将这些数据异步存储到数据库中达到持久化的目的。</p>
<h5 id="1-2-3-共享Session"><a href="#1-2-3-共享Session" class="headerlink" title="1.2.3 共享Session"></a>1.2.3 共享Session</h5><p>在分布式系统中，用户的每次请求会访问到不同的服务器，这就会导致session不同步的问题，假如一个用来获取用户信息的请求落在A服务器上，获取到用户信息后存入session。下一个请求落在B服务器上，想要从session中获取用户信息就不能正常获取了，因为用户信息的session在服务器A上，为了解决这个问题，使用redis集中管理这些session，将session存入redis，使用的时候直接从redis中获取就可以了。</p>
<h5 id="1-2-4-限速"><a href="#1-2-4-限速" class="headerlink" title="1.2.4 限速"></a>1.2.4 限速</h5><p>为了安全考虑，有些网站会对IP进行限制，限制同一IP在一定时间内访问次数不能超过n次。</p>
<h3 id="二-哈希"><a href="#二-哈希" class="headerlink" title="二 哈希"></a><strong>二 哈希</strong></h3><p>Redis中，哈希类型是指一个键值对的存储结构。</p>
<h4 id="2-1-内部编码"><a href="#2-1-内部编码" class="headerlink" title="2.1 内部编码"></a><strong>2.1 内部编码</strong></h4><p>哈希类型的内部编码有两种：</p>
<ul>
<li>ziplist（压缩列表）：当哈希类型元素个数小于<code>hash-max-ziplist-entries</code>配置（默认512个）同时所有值都小于<code>hash-max-ziplist-value</code>配置（默认64字节）时使用。ziplist使用更加紧凑的结构实现多个元素的连续存储，所以比hashtable更加节省内存。</li>
<li>hashtable（哈希表）：当ziplist不能满足要求时，会使用hashtable。</li>
</ul>
<h4 id="2-2-使用场景"><a href="#2-2-使用场景" class="headerlink" title="2.2 使用场景"></a><strong>2.2 使用场景</strong></h4><p>由于hash类型存储的是一个键值对，比如数据库有以下一个用户表结构</p>
<table>
<thead>
<tr>
<th align="left">id</th>
<th align="left">name</th>
<th align="left">age</th>
</tr>
</thead>
<tbody><tr>
<td align="left">1</td>
<td align="left">豆豆</td>
<td align="left">24</td>
</tr>
</tbody></table>
<p>将以上信息存入redis，用表明:id作为key，用户属性作为值：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">hset user:1 name 豆豆 age 24</span><br></pre></td></tr></table></figure>

<p>使用哈希存储会比字符串更加方便直观</p>
<h3 id="三-列表"><a href="#三-列表" class="headerlink" title="三 列表"></a><strong>三 列表</strong></h3><p>列表类型用来存储多个<strong>有序</strong>的字符串，一个列表最多可以存储<code>2^32-1</code>个元素，列表的两端都可以插入和弹出元素。</p>
<h4 id="3-1-内部编码"><a href="#3-1-内部编码" class="headerlink" title="3.1 内部编码"></a><strong>3.1 内部编码</strong></h4><p>列表的内部编码有两种：</p>
<ul>
<li>ziplist（压缩列表）：当哈希类型元素个数小于<code>list-max-ziplist-entries</code>配置（默认512个）同时所有值都小于<code>list-max-ziplist-value</code>配置（默认64字节）时使用。ziplist使用更加紧凑的结构实现多个元素的连续存储，所以比hashtable更加节省内存。</li>
<li>linkedlist（链表）：当ziplist不能满足要求时，会使用linkedlist。</li>
</ul>
<h4 id="3-2-使用场景"><a href="#3-2-使用场景" class="headerlink" title="3.2 使用场景"></a><strong>3.2 使用场景</strong></h4><h5 id="3-2-1-消息队列"><a href="#3-2-1-消息队列" class="headerlink" title="3.2.1 消息队列"></a>3.2.1 消息队列</h5><p>列表用来存储多个有序的字符串，既然是有序的，那么就满足消息队列的特点。使用<code>lpush</code>+<code>rpop</code>或者<code>rpush</code>+<code>lpop</code>实现消息队列。除此之外，redis支持阻塞操作，在弹出元素的时候使用阻塞命令来实现阻塞队列。</p>
<p>在蓝鲸SaaS开发中，Django的Celery本身不提供消息服务，但是可以方便的和第三方提供的消息中间件集成。包括，RabbitMQ、Redis等等。SaaS的本地开发中，Celery也默认选择了Redis作为消息队列。</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># Celery 消息队列设置 RabbitMQ</span></span><br><span class="line"><span class="comment"># BROKER_URL = 'amqp://guest:guest@localhost:5672//'</span></span><br><span class="line"><span class="comment"># Celery 消息队列设置 Redis</span></span><br><span class="line">BROKER_URL = <span class="string">"redis://localhost:6379/0"</span></span><br></pre></td></tr></table></figure>



<h5 id="3-2-2-栈"><a href="#3-2-2-栈" class="headerlink" title="3.2.2 栈"></a>3.2.2 栈</h5><p>由于列表存储的是有序字符串，满足队列的特点，也就能满足栈先进后出的特点，使用<code>lpush</code>+<code>lpop</code>或者<code>rpush</code>+<code>rpop</code>实现栈。</p>
<h5 id="3-2-3-文章列表"><a href="#3-2-3-文章列表" class="headerlink" title="3.2.3 文章列表"></a>3.2.3 文章列表</h5><p>因为列表的元素不但是有序的，而且还支持按照索引范围获取元素。因此我们可以使用命令<code>lrange key 0 9</code>分页获取文章列表</p>
<h3 id="四-集合"><a href="#四-集合" class="headerlink" title="四 集合"></a><strong>四 集合</strong></h3><p>集合类型也可以保存多个字符串元素，与列表不同的是，集合中不允许有重复元素并且集合中的元素是无序的。一个集合最多可以存储<code>2^32-1</code>个元素。</p>
<h4 id="4-1-内部编码"><a href="#4-1-内部编码" class="headerlink" title="4.1 内部编码"></a><strong>4.1 内部编码</strong></h4><p>集合类型的内部编码有两种：</p>
<ul>
<li>intset（整数集合）：当集合中的元素都是整数且元素个数小于<code>set-max-intset-entries</code>配置（默认512个）时，redis会选用intset来作为集合的内部实现，从而减少内存的使用。</li>
<li>hashtable（哈希表）：当intset不能满足要求时，会使用hashtable。</li>
</ul>
<h4 id="4-2-使用场景"><a href="#4-2-使用场景" class="headerlink" title="4.2 使用场景"></a><strong>4.2 使用场景</strong></h4><h5 id="4-2-1-用户标签"><a href="#4-2-1-用户标签" class="headerlink" title="4.2.1 用户标签"></a>4.2.1 用户标签</h5><p>例如一个用户对篮球、足球感兴趣，另一个用户对橄榄球、乒乓球感兴趣，这些兴趣点就是一个标签。有了这些数据就可以得到喜欢同一个标签的人，以及用户的共同感兴趣的标签。给用户打标签的时候需要①给用户打标签，②给标签加用户，需要给这两个操作增加事务。</p>
<ul>
<li>给用户打标签</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sadd user:1:tags tag1 tag2</span><br></pre></td></tr></table></figure>

<ul>
<li>给标签添加用户</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sadd tag1:users user:1</span><br><span class="line">sadd tag2:users user:1</span><br></pre></td></tr></table></figure>

<p>使用交集（sinter）求两个user的共同标签</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">sinter user:1:tags user:2:tags</span><br></pre></td></tr></table></figure>

<h5 id="4-2-2-抽奖功能"><a href="#4-2-2-抽奖功能" class="headerlink" title="4.2.2 抽奖功能"></a>4.2.2 抽奖功能</h5><p>集合有两个命令支持获取随机数，分别是：</p>
<ul>
<li>随机获取count个元素，集合元素个数不变</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">srandmember key [count]</span><br></pre></td></tr></table></figure>

<ul>
<li>随机弹出count个元素，元素从集合弹出，集合元素个数改变</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">spop key [count]</span><br></pre></td></tr></table></figure>

<p>用户点击抽奖按钮，参数抽奖，将用户编号放入集合，然后抽奖，分别抽一等奖、二等奖，如果已经抽中一等奖的用户不能参数抽二等奖则使用<code>spop</code>，反之使用<code>srandmember</code>。</p>
<h3 id="五-有序集合"><a href="#五-有序集合" class="headerlink" title="五 有序集合"></a><strong>五 有序集合</strong></h3><p>有序集合和集合一样，不能有重复元素。但是可以排序，它给每个元素设置一个score作为排序的依据。最多可以存储<code>2^32-1</code>个元素。</p>
<h4 id="5-1-内部编码"><a href="#5-1-内部编码" class="headerlink" title="5.1 内部编码"></a><strong>5.1 内部编码</strong></h4><p>有序集合类型的内部编码有两种：</p>
<ul>
<li>ziplist（压缩列表）：当有序集合的元素个数小于<code>list-max-ziplist-entries</code>配置（默认128个）同时所有值都小于<code>list-max-ziplist-value</code>配置（默认64字节）时使用。ziplist使用更加紧凑的结构实现多个元素的连续存储，更加节省内存。</li>
<li>skiplist（跳跃表）：当不满足ziplist的要求时，会使用skiplist。</li>
</ul>
<h4 id="5-2-使用场景"><a href="#5-2-使用场景" class="headerlink" title="5.2 使用场景"></a><strong>5.2 使用场景</strong></h4><h5 id="5-2-1-排行榜"><a href="#5-2-1-排行榜" class="headerlink" title="5.2.1 排行榜"></a>5.2.1 排行榜</h5><p>用户发布了n篇文章，其他人看到文章后给喜欢的文章点赞，使用score来记录点赞数，有序集合会根据score排行。流程如下</p>
<p>用户发布一篇文章，初始点赞数为0，即score为0</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">zadd user:article 0 a</span><br></pre></td></tr></table></figure>

<p>有人给文章a点赞，递增<code>1</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">zincrby user:article 1 a</span><br></pre></td></tr></table></figure>

<p>查询点赞前三篇文章</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">zrevrangebyscore user:article 0 2</span><br></pre></td></tr></table></figure>

<p>查询点赞后三篇文章</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">zrangebyscore user:article 0 2</span><br></pre></td></tr></table></figure>

<h5 id="5-2-2-延迟消息队列"><a href="#5-2-2-延迟消息队列" class="headerlink" title="5.2.2 延迟消息队列"></a>5.2.2 延迟消息队列</h5><p>下单系统，下单后需要在15分钟内进行支付，如果15分钟未支付则自动取消订单。将下单后的十五分钟后时间作为score，订单作为value存入redis，消费者轮询去消费，如果消费的大于等于这笔记录的score，则将这笔记录移除队列，取消订单。</p>
<h3 id="总结"><a href="#总结" class="headerlink" title="总结"></a><strong>总结</strong></h3><p>在开发中，字符串类型是用的最多的数据类型，导致我们忽视了redis的其他四种数据类型，在具体场景下选择具体的数据类型对提升redis性能有非常大的帮助。redis虽然支持消息队列的实现，但是并不支持ack。所以redis实现的消息队列不能保证消息的可靠性，除非自己实现消息确认机制，不过这非常麻烦，所以如果是重要的消息还是推荐使用专门的消息队列去做，如RabbitMQ、RocketMQ。</p>
<hr>
<p>参考链接：<a href="https://mp.weixin.qq.com/s/FsL-54ALoNUAPcft-u8Leg?v_p=86&WBAPIAnalysisOriUICodes=10000001_10000002&launchid=10000365--x&wm=3333_2001&aid=01A0GdQv0UejmN65Ntcd4pBeamMWOPan5tHaY8rK5tZGJgPOs.&from=10AA393010" target="_blank" rel="noopener">Redis 五大数据类型使用场景</a>  </p>

    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>Ryan Shu
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://notspr.com/2020/08/16/redis-use-case/" title="Redis修炼之使用场景">https://notspr.com/2020/08/16/redis-use-case/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fab fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>

        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/picture/weixin.png">
            <span class="icon">
              <i class="fab fa-weixin"></i>
            </span>

            <span class="label">WeChat</span>
          </a>
        </div>

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/Redis/" rel="tag"><i class="fa fa-tag"></i> Redis</a>
              <a href="/tags/Redis%E4%BD%BF%E7%94%A8%E5%9C%BA%E6%99%AF/" rel="tag"><i class="fa fa-tag"></i> Redis使用场景</a>
              <a href="/tags/NoSQL/" rel="tag"><i class="fa fa-tag"></i> NoSQL</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/08/12/redis-data-types/" rel="prev" title="Redis修炼之数据类型">
      <i class="fa fa-chevron-left"></i> Redis修炼之数据类型
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/08/20/celery/" rel="next" title="Python之Celery">
      Python之Celery <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#前言"><span class="nav-number">1.</span> <span class="nav-text">前言</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#使用场景"><span class="nav-number">2.</span> <span class="nav-text">使用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#一-字符串"><span class="nav-number">2.1.</span> <span class="nav-text">一 字符串</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-内部编码"><span class="nav-number">2.1.1.</span> <span class="nav-text">1.1 内部编码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-使用场景"><span class="nav-number">2.1.2.</span> <span class="nav-text">1.2 使用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-2-1-缓存"><span class="nav-number">2.1.2.1.</span> <span class="nav-text">1.2.1 缓存</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-2-2-计数"><span class="nav-number">2.1.2.2.</span> <span class="nav-text">1.2.2 计数</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-2-3-共享Session"><span class="nav-number">2.1.2.3.</span> <span class="nav-text">1.2.3 共享Session</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-2-4-限速"><span class="nav-number">2.1.2.4.</span> <span class="nav-text">1.2.4 限速</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二-哈希"><span class="nav-number">2.2.</span> <span class="nav-text">二 哈希</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-内部编码"><span class="nav-number">2.2.1.</span> <span class="nav-text">2.1 内部编码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-使用场景"><span class="nav-number">2.2.2.</span> <span class="nav-text">2.2 使用场景</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三-列表"><span class="nav-number">2.3.</span> <span class="nav-text">三 列表</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-内部编码"><span class="nav-number">2.3.1.</span> <span class="nav-text">3.1 内部编码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-2-使用场景"><span class="nav-number">2.3.2.</span> <span class="nav-text">3.2 使用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#3-2-1-消息队列"><span class="nav-number">2.3.2.1.</span> <span class="nav-text">3.2.1 消息队列</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-2-2-栈"><span class="nav-number">2.3.2.2.</span> <span class="nav-text">3.2.2 栈</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#3-2-3-文章列表"><span class="nav-number">2.3.2.3.</span> <span class="nav-text">3.2.3 文章列表</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#四-集合"><span class="nav-number">2.4.</span> <span class="nav-text">四 集合</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#4-1-内部编码"><span class="nav-number">2.4.1.</span> <span class="nav-text">4.1 内部编码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#4-2-使用场景"><span class="nav-number">2.4.2.</span> <span class="nav-text">4.2 使用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-1-用户标签"><span class="nav-number">2.4.2.1.</span> <span class="nav-text">4.2.1 用户标签</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#4-2-2-抽奖功能"><span class="nav-number">2.4.2.2.</span> <span class="nav-text">4.2.2 抽奖功能</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#五-有序集合"><span class="nav-number">2.5.</span> <span class="nav-text">五 有序集合</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#5-1-内部编码"><span class="nav-number">2.5.1.</span> <span class="nav-text">5.1 内部编码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#5-2-使用场景"><span class="nav-number">2.5.2.</span> <span class="nav-text">5.2 使用场景</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#5-2-1-排行榜"><span class="nav-number">2.5.2.1.</span> <span class="nav-text">5.2.1 排行榜</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#5-2-2-延迟消息队列"><span class="nav-number">2.5.2.2.</span> <span class="nav-text">5.2.2 延迟消息队列</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#总结"><span class="nav-number">2.6.</span> <span class="nav-text">总结</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Ryan Shu"
      src="/picture/avatar.jpg">
  <p class="site-author-name" itemprop="name">Ryan Shu</p>
  <div class="site-description" itemprop="description">全栈 | 硬件 | 篮球 | 游戏</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">40</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">34</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">82</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/sususama5555" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sususama5555" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:876324872@qq.com" title="E-Mail → mailto:876324872@qq.com" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://weibo.com/u/5330189327" title="Weibo → https:&#x2F;&#x2F;weibo.com&#x2F;u&#x2F;5330189327" rel="noopener" target="_blank"><i class="fab fa-weibo fa-fw"></i>Weibo</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://steamcommunity.com/profiles/76561198294148424/" title="steam → https:&#x2F;&#x2F;steamcommunity.com&#x2F;profiles&#x2F;76561198294148424&#x2F;" rel="noopener" target="_blank"><i class="fab fa-steam fa-fw"></i>steam</a>
      </span>
      <span class="links-of-author-item">
        <a href="/atom.xml" title="RSS → &#x2F;atom.xml"><i class="fa fa-rss fa-fw"></i>RSS</a>
      </span>
  </div>
  <div class="cc-license motion-element" itemprop="license">
    <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" class="cc-opacity" rel="noopener" target="_blank"><img src="/images/cc-by-nc-sa.svg" alt="Creative Commons"></a>
  </div>


  <div class="links-of-blogroll motion-element">
    <div class="links-of-blogroll-title"><i class="fa fa-link fa-fw"></i>
      友情链接
    </div>
    <ul class="links-of-blogroll-list">
        <li class="links-of-blogroll-item">
          <a href="http://ddoudou.xyz/" title="http:&#x2F;&#x2F;ddoudou.xyz" rel="noopener" target="_blank">豆豆的博客</a>
        </li>
    </ul>
  </div>

      </div>

      <!-- 音乐播放器 -->
      
           <div>
              <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width="210" height="110" src="//music.163.com/outchain/player?type=2&id=4226232&auto=1&height=66"></iframe>
           </div>
      

      <!-- 滚动条 -->
        <div class="back-to-top motion-element">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn/" rel="noopener" target="_blank">粤ICP备20063016号-2 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ryan Shu</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-area"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">180k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">2:44</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/pjax/pjax.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js"></script>
  <script src="//cdn.jsdelivr.net/gh/fancyapps/fancybox@3/dist/jquery.fancybox.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>

<script src="/js/utils.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>

<script src="/js/bookmark.js"></script>

  <script>
var pjax = new Pjax({
  selectors: [
    'head title',
    '#page-configurations',
    '.content-wrap',
    '.post-toc-wrap',
    '.languages',
    '#pjax'
  ],
  switches: {
    '.post-toc-wrap': Pjax.switches.innerHTML
  },
  analytics: false,
  cacheBust: false,
  scrollTo : !CONFIG.bookmark.enable
});

window.addEventListener('pjax:success', () => {
  document.querySelectorAll('script[data-pjax], script#page-configurations, #pjax script').forEach(element => {
    var code = element.text || element.textContent || element.innerHTML || '';
    var parent = element.parentNode;
    parent.removeChild(element);
    var script = document.createElement('script');
    if (element.id) {
      script.id = element.id;
    }
    if (element.className) {
      script.className = element.className;
    }
    if (element.type) {
      script.type = element.type;
    }
    if (element.src) {
      script.src = element.src;
      // Force synchronous loading of peripheral JS.
      script.async = false;
    }
    if (element.dataset.pjax !== undefined) {
      script.dataset.pjax = '';
    }
    if (code !== '') {
      script.appendChild(document.createTextNode(code));
    }
    parent.appendChild(script);
  });
  NexT.boot.refresh();
  // Define Motion Sequence & Bootstrap Motion.
  if (CONFIG.motion.enable) {
    NexT.motion.integrator
      .init()
      .add(NexT.motion.middleWares.subMenu)
      .add(NexT.motion.middleWares.postList)
      .bootstrap();
  }
  NexT.utils.updateSidebarPosition();
});
</script>




  
  <script data-pjax>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/js/local-search.js"></script>













    <div id="pjax">
  

  

    </div>
</body>
</html>
